import { applyTransform } from "ol/extent";
import TileLayer from "ol/layer/Tile";
import { Tile, TileImage, XYZ } from "ol/source";
import TileGrid from "ol/tilegrid/TileGrid";
import baiduMecator from './baiduMecator'
import gcj02Mecator from "./gcj02Mecator";

  /*定义百度地图分辨率与瓦片网格*/
  var resolutions = [];
  for (var i = 0; i <= 18; i++) {
    resolutions[i] = Math.pow(2, 18 - i);
  }

  var tilegrid = new TileGrid({
    origin: [0, 0],
    resolutions: resolutions
  });
  var source = new XYZ({
    projection: baiduMecator,
    tileGrid: tilegrid,
    tilePixelRatio: 2,
    wrapX: true, // 是否水平包裹世界。
    crossOrigin: 'anonymous' ,// 图片跨域允许
    tileUrlFunction: function (tileCoord, pixelRatio, proj) {
      //  openlayers6的版本
      let z = tileCoord[0];
      let x = tileCoord[1];
      let y = -tileCoord[2] - 1;
      if (x < 0) x = "M" + (-x);
      if (y < 0) y = "M" + (-y);
      let num = Math.ceil(Math.random() * 3);
      return (
        "http://maponline" +
        num +
        ".bdimg.com/tile/?qt=vtile&x=" +
        x +
        "&y=" +
        y +
        "&z=" +
        z +
        "&styles=pl&udt=20220818&scaler=2&p=0"
      );
    }
  });


const createBaiduLayer = () =>{
  
  var mapLayer = new TileLayer({
    zIndex: 0, // 底图图层层级
    visible:true, //底图显示隐藏
    className: 'ol-layer ' + 'baidu',
    mapName:'baidu',
    source: source
  });

  return mapLayer;
}
const createAmapLayer = () =>{
  var mapLayer = createBaseLayer('amap',
  'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
   gcj02Mecator,true
  )
  return mapLayer;
}

const createTiandituSatelliteLayer = () =>{
  var mapLayer = createBaseLayer('tianditusatellite',
  'https://t{1-7}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=5281d481de6e8ffa88add376ade28968',
   'EPSG:3857',true
  )
  return mapLayer;
}

const createGoogleSatelliteLayer = () =>{
  var mapLayer = createBaseLayer('googlesatellite',
  'http://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&src=app&scale=1',
   gcj02Mecator,true
  )
  return mapLayer;
}

const createGoogleannoSatelliteLayer = () =>{
  var mapLayer = createBaseLayer('googleannosatellite',
  'http://gac-geo.googlecnapps.cn/maps/vt?lyrs=y&hl=zh-CN&gl=CN&x={x}&y={y}&z={z}&src=app&scale=1',
   gcj02Mecator,true
  )
  return mapLayer;
}

//创建底图图层
const createBaseLayer=(mapName,url,projection,visible = true) =>{
		return new TileLayer({
			zIndex: 0, // 底图图层层级
			visible, //底图显示隐藏
			className: 'ol-layer ' + mapName,
			mapName,
			source: new XYZ({
				url,
				projection,
				wrapX: true, // 是否水平包裹世界。
				crossOrigin: 'anonymous' // 图片跨域允许
			})
	})
}
export  {createBaiduLayer,createAmapLayer,createTiandituSatelliteLayer,
  createGoogleSatelliteLayer,createGoogleannoSatelliteLayer}